package com.joint.web.action.finance;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.finance.CalculationYear;
import com.joint.core.entity.finance.ModifyYear;
import com.joint.core.service.CalculationYearService;
import com.joint.core.service.ModifyYearService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/3/7.
 */
@ParentPackage("finance")
public class AjaxModifyyearAction extends BaseFlowAction {
    @Resource
    private ModifyYearService modifyYearService;
    @Resource
    private CalculationYearService calculationYearService;

    private ModifyYear modifyYear;
    private CalculationYear calculationYear;
    private Users loginUser;
    private String viewtype;
    private int ifCentralStaff;
    private int numStatus;
    private String newBudgetfileId;
    private String newBudgetIds;
    private List<Map<String,Object>> calculationYearList;
    private String calculationYearId;
    private String calculationYearText;

    public String execute(){
        return "modifyyear";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        if (StringUtils.isNotEmpty(parentId)){
            calculationYear = calculationYearService.get(parentId);
            params.put("calculationYear",calculationYear);
        }
        params.put("company",com);
        params.put("state", BaseEnum.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("invalid", false);
                pager=modifyYearService.findByPagerAndLimit(false, "modifyyear", pager, params);
            }else if(viewtype.equals("2")){
                //已通过
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("invalid", false);
                pager=modifyYearService.findByPagerAndFinish( "modifyyear", pager, params);
            }else if(viewtype.equals("3")){
                //已失效
                params.put("invalid", true);
                pager=modifyYearService.findByPagerAndLimit(true, "modifyyear", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=modifyYearService.findByPagerAndLimit(true, "modifyyear", pager, params);
        }
        List<ModifyYear> mYearList;
        if (pager.getTotalCount() > 0){
            mYearList = (List<ModifyYear>) pager.getList();
        }else{
            mYearList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(ModifyYear m:mYearList){
            String state=m.getProcessState().name();
            rMap = new HashMap<String,Object>();
            rMap.put("id", m.getId());
            rMap.put("year", m.getYear());
            rMap.put("createDate", DataUtil.DateToString(m.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("creater",m.getCreater()==null?"":m.getCreater().getName());
            if (StringUtils.isNotEmpty(m.getProcessState().name())) {
                rMap.put("state", m.getProcessState().value());
//                if (state.equals("Finished")) {
//                    rMap.put("state", m.getProcessState().value());
//                } else if (state.equals("Running")) {
//                    rMap.put("state", m.getProcessState().value());
//                } else if (state.equals("Backed")) {
//                    rMap.put("state", m.getProcessState().value());
//                }
            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String input(){
        newBudgetfileId="";
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
        params.put("invalid", false);
        Company company = usersService.getCompanyByUser();
        List<CalculationYear> list = (List<CalculationYear>)calculationYearService.findByPagerAndCompany(null, null, company, params).getList();
        calculationYearList= Lists.newArrayList();
        Map<String,Object> rmap;
        if(StringUtils.isNotEmpty(parentId)){
            calculationYear=calculationYearService.get(parentId);
        }
        if(StringUtils.isNotEmpty(keyId)){
            modifyYear=modifyYearService.get(keyId);
            if(modifyYear.getNewBudget()!=null&&modifyYear.getNewBudget().size()>0){
                for(FileManage n:modifyYear.getNewBudget()){
                    newBudgetfileId+=n.getId()+",";
                }
            }
            for(CalculationYear c:list){
                rmap= Maps.newHashMap();
                rmap.put("id",c.getId());
                rmap.put("name",c.getName());
                if(modifyYear.getCalculationYear()!=null && StringUtils.equals(c.getId(), modifyYear.getCalculationYear().getId())){
                    rmap.put("selected","selected");
                }
                calculationYearList.add(rmap);
            }
        }else{
            if(list.size()>0){
                for(CalculationYear c:list){
                    rmap= Maps.newHashMap();
                    rmap.put("id",c.getId());
                    rmap.put("name",c.getName());
                    rmap.put("selected","");
                    calculationYearList.add(rmap);
                }
            }
        }
        return "input";
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)){
            modifyYear=modifyYearService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            newBudgetfileId="";
            if(modifyYear.getNewBudget()!=null&&modifyYear.getNewBudget().size()>0){
                for(FileManage n:modifyYear.getNewBudget()){
                    newBudgetfileId+=n.getId()+",";
                }
            }
            calculationYearText=modifyYear.getCalculationYear().getName();
        }
        return "read";
    }

    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                modifyYearService.update(modifyYear);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                various.put("curDutyId", curDutyId);
                modifyYearService.save(modifyYear, "modifyyear", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    public void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            modifyYear=modifyYearService.get(keyId);
        }else{
            modifyYear=new ModifyYear();
            modifyYear.setCreater(usersService.getLoginInfo());
        }
        modifyYear.setCompany(usersService.getLoginInfo().getCompany());

        List<FileManage> newBudgetList=Lists.newArrayList();
        if(StringUtils.isNotEmpty(newBudgetIds)){
            for(String n:newBudgetIds.split(",")){
                newBudgetList.add(fileManageService.get(n.trim()));
            }
        }
        modifyYear.setNewBudget(newBudgetList);
        modifyYear.setCalculationYear(calculationYearService.get(parentId));
        String year= String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        modifyYear.setYear(year);
    }

    public String commit(){
        System.out.println("###刚刚提交");
        setData();
        ifCentralStaff=0;
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi" + duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        if(ifCentralStaff==1){
            var1.put("numStatus",3);
            var2.put("numStatus",3);
        }else{
            var1.put("numStatus",1);
            var2.put("numStatus",1);
        }
        var2.put("curDutyId", curDutyId);
        var2.put("ifCentralStaff", ifCentralStaff);

        List<String> list=Lists.newArrayList();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Department> deptSet=dept.getChildren();
            for(Department cdept:deptSet){
                if(cdept.getName().contains("财务科")){
                    Set<Power> powers = cdept.getPowerSet();
                    for(Power power:powers){
                        if(power.getPost().getName().equals("科长")){
                            List<Users> usersList=dutyService.getPersons(cdept,power.getPost());
                            for(Users user:usersList){
                                list.add(user.getId().trim());
                            }
                        }
                    }
                }

            }
        }
        var1.put("approver", list);
        var2.put("approver", list);
        List<String> list2=Lists.newArrayList();
        for(Duty duty:dutySet){
            Department dept=duty.getDepartment().getParent()==null?duty.getDepartment():duty.getDepartment().getParent();
            Set<Power> powers = dept.getPowerSet();
            for(Power power:powers){
                if(power.getPost().getName().equals("总经理")){
                    List<Users> usersList=dutyService.getPersons(dept, power.getPost());
                    for(Users user:usersList){
                        list2.add(user.getId().trim());
                    }
                }
            }
        }
        var1.put("approver1", list2);
        var2.put("approver1", list2);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                modifyYearService.approve(modifyYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId = modifyYearService.commit(modifyYear, "modifyyear", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve1(){
        System.out.println("========app1===下属公司财务科科长===");
        ifCentralStaff=0;
        modifyYear = modifyYearService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                System.out.println("我的部门名称是：---------"+duty.getDepartment().getName());
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    ifCentralStaff=1;
                    break;
                }
            }
        }
        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                modifyYearService.approve(modifyYear, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve2() {
        System.out.println("========app2===下属公司总经理===");
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        modifyYear = modifyYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 3);
        //  var2.put("curDutyId", curDutyId);
        try {
            modifyYearService.approve(modifyYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        System.out.println("========app3===财务科科长===");
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        modifyYear = modifyYearService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            modifyYearService.approve(modifyYear, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve4() {
        System.out.println("========app3===中心主任/中心书记\n===");
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        modifyYear = modifyYearService.get(keyId);
        String name=modifyYear.getCalculationYear().getName();
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 5);
        //  var2.put("curDutyId", curDutyId);
        try {
            modifyYearService.approve(modifyYear, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            updateFile();
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", name+"附件已修改！", "操作状态");
    }

    /**
     * 最后修改全年预决算报表的附件
     */
    public void updateFile(){
        modifyYear=modifyYearService.get(keyId);
        CalculationYear calculationYear=modifyYear.getCalculationYear();
        String keyId=calculationYear.getId();
        String sql="insert into sk_calculationyear_budget (id,budgetId) values ";
        for(FileManage b:modifyYear.getNewBudget()){
            sql+="('"+calculationYear.getId()+"','"+b.getId()+"'),";
        }
        sql=sql.substring(0,sql.length()-1);
        modifyYearService.updateCalFile(keyId, sql);
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            modifyYear = modifyYearService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("modifyyear");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            modifyYearService.reject(modifyYear, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            modifyYear = modifyYearService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("modifyyear");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            modifyYearService.deny(modifyYear, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    /**
     * 失效
     * @return
     */
    public String doInvalid(){
        if(StringUtils.isNotEmpty(keyId)) {
            modifyYear = modifyYearService.get(keyId);
            modifyYear.setInvalid(true);
            modifyYearService.update(modifyYear);
        }
        return ajaxHtmlCallback("200", "操作成功！", "操作状态");
    }



    public ModifyYear getModifyYear() {
        return modifyYear;
    }

    public void setModifyYear(ModifyYear modifyYear) {
        this.modifyYear = modifyYear;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public String getNewBudgetfileId() {
        return newBudgetfileId;
    }

    public void setNewBudgetfileId(String newBudgetfileId) {
        this.newBudgetfileId = newBudgetfileId;
    }

    public List<Map<String, Object>> getCalculationYearList() {
        return calculationYearList;
    }

    public void setCalculationYearList(List<Map<String, Object>> calculationYearList) {
        this.calculationYearList = calculationYearList;
    }

    public String getNewBudgetIds() {
        return newBudgetIds;
    }

    public void setNewBudgetIds(String newBudgetIds) {
        this.newBudgetIds = newBudgetIds;
    }

    public String getCalculationYearId() {
        return calculationYearId;
    }

    public void setCalculationYearId(String calculationYearId) {
        this.calculationYearId = calculationYearId;
    }

    public String getCalculationYearText() {
        return calculationYearText;
    }

    public void setCalculationYearText(String calculationYearText) {
        this.calculationYearText = calculationYearText;
    }

    public CalculationYear getCalculationYear() {
        return calculationYear;
    }

    public void setCalculationYear(CalculationYear calculationYear) {
        this.calculationYear = calculationYear;
    }
}
